package org.damazio.bhtranscams;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

/**
 * Overlay which is drawn over the map to represent each camera.
 * 
 * @author rdamazio
 */
public class CamerasMapOverlay extends Overlay {

  private static final double MAX_TAP_DISTANCE_KM = 3;
  // Rough approximation - one degree = 50 nautical miles
  private static final double MAX_TAP_DISTANCE_DEGREES = MAX_TAP_DISTANCE_KM * 0.5399568 * 50;
  private final GeoPoint geoPoint;
  private final Context context;

  /**
   * @param context the context in which to display the overlay
   * @param geoPoint the geographical point where the overlay is located
   */
  public CamerasMapOverlay(Context context, GeoPoint geoPoint) {
    this.context = context;
    this.geoPoint = geoPoint;
  }

  @Override
  public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
    super.draw(canvas, mapView, shadow);

    // Convert geo coordinates to screen pixels
    Point screenPoint = new Point();
    mapView.getProjection().toPixels(geoPoint, screenPoint);

    // Read the image
    Bitmap markerImage = BitmapFactory.decodeResource(context.getResources(),
        R.drawable.camera_icon);

    // Draw it, centered around the given coordinates
    canvas.drawBitmap(markerImage,
        screenPoint.x - markerImage.getWidth() / 2,
        screenPoint.y - markerImage.getHeight() / 2, null);
    return true;
  }

  @Override
  public boolean onTap(GeoPoint p, MapView mapView) {
    // Show closest camera
    ClosestCameraPicker cameraPicker = new ClosestCameraPicker(context, MAX_TAP_DISTANCE_DEGREES);
    cameraPicker.showClosestCamera(p);
    return true;
  }
}